/**
 * 
 */
package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author Fleischhacker
 *
 *	Startup Class for Server
 *	Checks the given Parameter and configurates the Server with the given Parameter
 *	If the Parameter is neither a Number nor the count is equal 1 the Server will not startup
 *		and prints the syntax
 *	Checks if the User hits the ENTER Key in Order to Shutdown the Server
 */
public class StartUp {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		for(String s : args)
			System.out.println(s);
		int port = checkAndParse(args);
		if(port != -1){
			System.out.println("============================================================");
			System.out.println("= Server starting!                                         =");
			System.out.println("= Server Port: ["+port+"]                                     =");
			ServerPool sp = new ServerPool(port);
			sp.start();
			System.out.println("= Server is ready to recieve incoming requests!            =");
			System.out.println("= In order to STOP the SERVER please hit the ENTER KEY!    =");
			checkForShutdownByEnter();
			sp.shutdown();
			System.out.println("= Server stopped!                                          =");
			System.out.println("============================================================");
		}
	}

	/**
	 * Checks the Params of the main
	 * 		Awaited Parameters: NUMBER
	 * 		Awaited Syntax: java server.StartUp NUMBER
	 * @param args - given Params
	 * @return -1 if the given Argument(s) is no Number
	 * 			Portnumber otherwise
	 */
	@SuppressWarnings("finally")
	private static int checkAndParse(String[] args){
		try{
			if(args.length == 1){
				return Integer.parseInt(args[0]);
			}
			else
				throw new NumberFormatException();//Abusing Exception for less Code
		}catch(NumberFormatException nfe){
			System.out.println("Argument error!\nSyntax: java server.StartUp NUMBER[1]\nParameter Information:\n + [1] Portnumber");
		}catch(Exception e){
			e.printStackTrace();
		}
		return -1;
	}
	
	/**
	 * Waits for the User to hit the ENTER KEY in order to get out of this Function
	 * @return True cuz it can
	 */
	private static boolean checkForShutdownByEnter(){
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		while(true){
			String s = null;
			try{
				if(in.readLine().length() == 0)
					return true;
			}catch(IOException ioe){
				System.out.println("ERROR @StartUp.checkForShutdownByEnter():"+ioe.getMessage());
			}
		}
	}
}
